import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Scene06UndoRedo extends StatefulWidget {
  const Scene06UndoRedo({super.key});
  @override
  State<Scene06UndoRedo> createState() => _Scene06UndoRedoState();
}

class _Scene06UndoRedoState extends State<Scene06UndoRedo>
    implements DeltaTextInputClient {
  late final TextInputConnection _conn;
  TextEditingValue _value = const TextEditingValue(text: '');

  /// 历史栈：用 [old, new] 表示一次撤销单元
  final List<List<String>> _history = [];
  int _cursor = -1;

  final List<String> _logs = [];

  /* === DeltaTextInputClient === */
  @override
  TextEditingValue get currentTextEditingValue => _value;

  @override
  void updateEditingValueWithDeltas(List<TextEditingDelta> deltas) {
    _logs.add('updateEditingValueWithDeltas');
    // 把真实输入加入历史
    for (final d in deltas) {
      if (d is TextEditingDeltaInsertion) {
        _pushHistory(d.oldText, d.textInserted);
        _logs.add('输入: "${d.textInserted}"');
      }
    }
    setState(() {
      for (final d in deltas) _value = d.apply(_value);
    });
  }

  /* 其余空实现，保证零报错 */
  @override
  void updateEditingValue(TextEditingValue value) {
    _logs.add('updateEditingValue');

  }
  @override
  void performAction(TextInputAction action) {
    _logs.add('performAction');

  }
  @override
  void connectionClosed() {
    _logs.add('connectionClosed');
  }

  @override
  void insertContent(KeyboardInsertedContent content) {
    _logs.add('insertContent');
  }
  @override
  void insertTextPlaceholder(Size size) {
    _logs.add('insertTextPlaceholder');
  }
  @override
  void performPrivateCommand(String action, Map<String, dynamic> data) {
    _logs.add('performPrivateCommand');
  }
  @override
  void performSelector(String selectorName) {
    _logs.add('performSelector');
  }
  @override
  void removeTextPlaceholder() {
    _logs.add('removeTextPlaceholder');
  }
  @override
  void showAutocorrectionPromptRect(int start, int end) {
    _logs.add('showAutocorrectionPromptRect');
  }
  @override
  void showToolbar() {
    _logs.add('showToolbar');
  }
  @override
  void updateFloatingCursor(RawFloatingCursorPoint point) {
    _logs.add('updateFloatingCursor');
  }

  /* === 生命周期 === */
  @override
  void initState() {
    super.initState();
    _conn = TextInput.attach(
      this,
      const TextInputConfiguration(enableDeltaModel: true),
    )
      ..show()
      ..setEditingState(_value);
  }

  @override
  void dispose() {
    _conn.close();
    super.dispose();
  }

  /* === 历史管理 === */
  void _pushHistory(String oldText, String newText) {
    // 丢弃当前指针后面的历史（重做失效）
    _history.removeRange(_cursor + 1, _history.length);
    _history.add([oldText, newText]);
    _cursor = _history.length - 1;
  }

  /* 手动触发撤销 / 重做 */
  void _undo() {
    if (_cursor < 0) return;
    final [old, _] = _history[_cursor];
    final delta = TextEditingDeltaReplacement(
      oldText: _value.text,
      replacedRange: TextRange(start: 0, end: _value.text.length),
      replacementText: old,
      selection: TextSelection(baseOffset: 0, extentOffset: _value.text.length),
      composing: TextRange(start: 0, end: _value.text.length),
    );
    updateEditingValueWithDeltas([delta]);
    _logs.add('撤销 → "$old"');
    _cursor--;
  }

  void _redo() {
    if (_cursor >= _history.length - 1) return;
    _cursor++;
    final [_, newText] = _history[_cursor];
    final delta = TextEditingDeltaReplacement(
      oldText: _value.text,
      replacedRange: TextRange(start: 0, end: _value.text.length),
      replacementText: newText,
      selection: TextSelection(baseOffset: 0, extentOffset: _value.text.length),
      composing: TextRange(start: 0, end: _value.text.length),
    );
    updateEditingValueWithDeltas([delta]);
    _logs.add('重做 → "$newText"');
  }

  /* === UI === */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('撤销/重做 Delta 场景')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.all(8),
              itemCount: _logs.length,
              itemBuilder: (_, i) => Text(_logs[i],
                  style: const TextStyle(fontSize: 12, fontFamily: 'monospace')),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12),
            child: TextField(
              controller: TextEditingController.fromValue(_value),
              maxLines: null,
              decoration: const InputDecoration(
                hintText: '先输入再点撤销/重做',
                border: OutlineInputBorder(),
              ),
              onChanged: (_) {},
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(onPressed: _undo, child: const Text('撤销')),
              ElevatedButton(onPressed: _redo, child: const Text('重做')),
            ],
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement currentAutofillScope
  AutofillScope? get currentAutofillScope => throw UnimplementedError();

  @override
  void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
    // TODO: implement didChangeInputControl
  }
}